package com.ics.cmsadmin.modules.agent.service.impl;

import com.ics.cmsadmin.frame.api.AliBabaApi;
import com.ics.cmsadmin.frame.api.CcdcapiResponse;
import com.ics.cmsadmin.frame.constant.Constants;
import com.ics.cmsadmin.frame.core.bean.LoginSearchBean;
import com.ics.cmsadmin.frame.core.bean.PageBean;
import com.ics.cmsadmin.frame.core.bean.PageResult;
import com.ics.cmsadmin.frame.core.enums.ApiResultEnum;
import com.ics.cmsadmin.frame.core.exception.CmsException;
import com.ics.cmsadmin.modules.agent.bean.*;
import com.ics.cmsadmin.modules.agent.service.AgentInfoService;
import com.ics.cmsadmin.modules.auth.bean.SysUser;
import com.ics.cmsadmin.modules.system.emums.SequenceNumberEnum;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static com.ics.cmsadmin.modules.agent.steward.AgentRepositories.agentDaySummaryDao;
import static com.ics.cmsadmin.modules.agent.steward.AgentRepositories.agentInfoDao;
import static com.ics.cmsadmin.modules.agent.steward.AgentServices.agentAccountService;
import static com.ics.cmsadmin.modules.agent.steward.AgentServices.agentShareRuleService;
import static com.ics.cmsadmin.modules.auth.steward.AuthServices.userService;
import static com.ics.cmsadmin.modules.system.steward.SystemServices.sequenceNumberService;

/**
 * a_agent_info
 * Created bylvsw on 2018-37-29 16:09:14.
 */
@Log4j2
@Service
public class AgentInfoServiceImpl implements AgentInfoService {

    @Override
    public AgentInfoBean queryByUserId(String userId) {
        if (StringUtils.isBlank(userId)) {
            return null;
        }
        return agentInfoDao.findOne(AgentInfoBean.builder().userId(userId).build());
    }

    @Override
    public AgentDto queryMoreInfoByUserId(String userId) {
        AgentInfoBean agentInfoBean = queryByUserId(userId);
        if (agentInfoBean == null) {
            return null;
        }
        SysUser userInfo = userService.queryById(userId);
        AgentShareRuleBean agentShareRuleBean = agentShareRuleService.queryByAgentNo(agentInfoBean.getAgentNo());
        AgentAccountBean agentAccountBean = agentAccountService.queryByAgentNo(agentInfoBean.getAgentNo());
        AgentDaySummaryBean agentDaySummaryBean = summaryAgentData(agentInfoBean.getAgentNo());
        return AgentDto.builder()
            .agentInfo(agentInfoBean)
            .account(agentAccountBean)
            .userInfo(userInfo)
            .shareRule(agentShareRuleBean)
            .agentDaySummary(agentDaySummaryBean)
            .build();
    }

    /**
     * 查询分销商汇总信息
     */
    public AgentDaySummaryBean summaryAgentData(String agentNo) {
        AgentDaySummaryBean shareMoneySummary = Optional.ofNullable(agentDaySummaryDao.summaryShareMoney(agentNo))
            .orElse(new AgentDaySummaryBean());

        // 今日购买人数
        int buyerNewly = agentDaySummaryDao.countBuyerNumToday(agentNo);
        // 购买总人数
        int buyerCusm = agentDaySummaryDao.countAllBuyerNum(agentNo);
        // 今日关注人数
        int funsNewly = agentDaySummaryDao.countFansNumToday(agentNo);
        // 关注总人数
        int funsCusm = agentDaySummaryDao.countAllFansNum(agentNo);
        // 今日分润
        BigDecimal shareMoney = agentDaySummaryDao.countShareMoneyToday(agentNo);

        LoginSearchBean loginSearchBean = new LoginSearchBean();
        loginSearchBean.setLoginAgentNo(agentNo);
        // 下级今日购买人数
        int childBuyerNewly = agentDaySummaryDao.countChildrenBuyerNumToday(loginSearchBean);
        // 下级购买总人数
        int childBuyerCusm = agentDaySummaryDao.countChildrenAllBuyerNum(loginSearchBean);
        // 下级今日关注人数
        int childFunsNewly = agentDaySummaryDao.countChildrenFansNumToday(loginSearchBean);
        // 下级关注总人数
        int childFunsCusm = agentDaySummaryDao.countChildrenAllFansNum(loginSearchBean);

        return AgentDaySummaryBean.builder().allShareMoneyCusm(shareMoneySummary.getAllShareMoneyCusm())
            .selfShareMoneyNewly(shareMoney)
            .selfShareMoneyCusm(shareMoneySummary.getSelfShareMoneyCusm())
            .childShareMoneyCusm(shareMoneySummary.getChildShareMoneyCusm())
            .buyerNewly(buyerNewly)
            .buyerCusm(buyerCusm)
            .funsNewly(funsNewly)
            .funsCusm(funsCusm)
            .childBuyerNewly(childBuyerNewly)
            .childBuyerCusm(childBuyerCusm)
            .childFunsNewly(childFunsNewly)
            .childFunsCusm(childFunsCusm)
            .build();
    }

    @Override
    public AgentInfoBean queryById(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        return agentInfoDao.queryById(id);
    }

    @Override
    public AgentDto queryMoreInfoById(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        AgentInfoBean agentInfoBean = agentInfoDao.queryById(id);
        if (agentInfoBean == null) {
            return null;
        }
        SysUser userInfo = userService.queryById(agentInfoBean.getUserId());
        AgentShareRuleBean shareRuleBean = agentShareRuleService.queryByAgentNo(agentInfoBean.getAgentNo());
        AgentAccountBean agentAccountBean = agentAccountService.queryByAgentNo(agentInfoBean.getAgentNo());
        return AgentDto.builder()
            .agentInfo(agentInfoBean)
            .userInfo(userInfo)
            .shareRule(shareRuleBean)
            .account(agentAccountBean)
            .build();
    }

    @Override
    public PageResult<AgentInfoBean> listByLoginUserId(AgentInfoBean bean, String loginUserId, PageBean page) {
        return listByLoginUserId(bean, loginUserId, page, agentInfoDao);
    }

    @Override
    public boolean insertAgent(AgentDto bean) {
        if (bean == null) {
            return false;
        }
        String agentNo = sequenceNumberService.newSequenceNumber(SequenceNumberEnum.AGENT);
        // 1，创建分销商登陆信息
        addLoginUser(bean.getUserInfo());
        bean.getAgentInfo().setUserId(bean.getUserInfo().getUserId());
        bean.getAgentInfo().setAgentNo(agentNo);
        // 2. 创建分销商基本信息
        addAgentBaseInfo(bean.getAgentInfo());
        // 3 新增分销商分润账户
        agentAccountService.insert(AgentAccountBean
            .builder()
            .agentNo(agentNo)
            .build());
        return true;
    }

    private void addAgentBaseInfo(AgentInfoBean bean) {
        if (StringUtils.isNotBlank(bean.getParentId()) && !StringUtils.equals("0", bean.getParentId())) {
            AgentInfoBean parentAgent = agentInfoDao.queryById(bean.getParentId());
            if (parentAgent == null) {
                throw new CmsException(ApiResultEnum.INSERT_TABLE_ITEM_FAIL, "父级分销商不存在");
            }
        } else {
            bean.setParentId("0");
        }
        validateAccountNo(bean);
        agentInfoDao.insert(bean);
    }

    private void validateAccountNo(AgentInfoBean bean) {
        CcdcapiResponse ccdcapiResponse = AliBabaApi.validateAndCacheCardInfo(bean.getAccountNo());
        if (ccdcapiResponse == null) {
            return;
        }
        if (!ccdcapiResponse.isValidated()) {
            throw new CmsException(ApiResultEnum.VALIDATE_ERROR, "请输入正确的银行卡");
        }
        bean.setBank(ccdcapiResponse.getBank());
        bean.setCardType(ccdcapiResponse.getCardType());
    }

    private SysUser addLoginUser(SysUser userInfo) {
        if (userInfo == null) {
            throw new CmsException(ApiResultEnum.INSERT_TABLE_ITEM_FAIL, "分销商基本信息为空");
        }
        userInfo.setUserType(Constants.USER_TYPE_AGENT);      // 标识登陆用户为分销商
        userInfo.setOrgId("agent");
        userService.insert(userInfo);
        return userInfo;
    }

    @Override
    public boolean updateAgent(String id, AgentDto bean) {
        if (StringUtils.isBlank(id) || bean == null || queryById(id) == null) {
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "参数有误");
        }
        // 1，更新分销商登陆信息
        updateLoginUser(bean.getUserInfo());
        // 2. 更新分销商基本信息
        updateAgentBaseInfo(bean.getAgentInfo());
        return true;
    }

    private void updateAgentBaseInfo(AgentInfoBean bean) {
        if (StringUtils.isBlank(bean.getAgentNo())) {
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "分销商编号为空");
        }
        validateAccountNo(bean);
        agentInfoDao.update(bean.getAgentNo(), bean);
    }

    private void updateLoginUser(SysUser userInfo) {
        if (userInfo == null || StringUtils.isBlank(userInfo.getUserId())) {
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "用户信息为空");
        }
        userService.update(userInfo.getUserId(), userInfo);
    }

    @Override
    public List<AgentInfoBean> queryLevelAgent() {
        List<AgentInfoBean> result = new ArrayList<>();
        result.add(AgentInfoBean.builder().agentNo("0").name("顶级分销商").build());
        List<AgentInfoBean> list = agentInfoDao.list(AgentInfoBean.builder().build(), new PageBean(1, Integer.MAX_VALUE));
        if (list != null) {
            result.addAll(list);
        }
        return result;
    }

    @Override
    public boolean resetPassword(String agentNo, String loginUserId) {
        if (StringUtils.isBlank(agentNo)) {
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "该分销商不存在");
        }
        AgentInfoBean agentInfoBean = queryById(agentNo);
        if (agentInfoBean == null) {
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "该分销商不存在");
        }
        return userService.resetPassword(agentInfoBean.getUserId());
    }

    @Override
    public boolean disable(String id) {
        AgentInfoBean agentInfoBean = queryById(id);
        if (agentInfoBean == null) {
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "该分销商不存在");
        }
        agentInfoDao.update(id, AgentInfoBean.builder().status(Constants.DISABLE_STATUS).build());
        userService.delete(agentInfoBean.getUserId());
        return true;
    }

    @Override
    public boolean enable(String id) {
        AgentInfoBean agentInfoBean = queryById(id);
        if (agentInfoBean == null) {
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "该分销商不存在");
        }
        agentInfoDao.update(id, AgentInfoBean.builder().status(Constants.ENABLE_STATUS).build());
        userService.recovery(agentInfoBean.getUserId());
        return true;
    }

    @Override
    public boolean changeSalesman(String agentNo, String salesmane) {
        AgentInfoBean agentInfoBean = queryById(agentNo);
        if (agentInfoBean == null) {
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "该分销商不存在");
        }
        SysUser salesmaneUserInfo = userService.queryById(salesmane);
        if (salesmaneUserInfo == null || !StringUtils.equals(Constants.USER_TYPE_ADMIN, salesmaneUserInfo.getUserType())) {
            throw new CmsException(ApiResultEnum.UPDATE_TABLE_ITEM_FAIL, "无法将该分销商分配该业务员");
        }
        return agentInfoDao.update(agentNo, AgentInfoBean.builder().salesman(salesmane).build()) == 1;
    }
}
